package operation;

import car.Cars;
import car.Vehicle;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class ModifyVehicle implements IOperation {
    Scanner scanner = new Scanner(System.in);

    public void updateVehicleInDatabase(Vehicle vehicle) {
        try (Connection connection = DBHelper.getConnection()) {
            String sql = "UPDATE vehicle SET brand = ?, type = ?, perRent = ? WHERE vehicleId = ?";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {
                statement.setString(1, vehicle.getBrand());
                statement.setString(2, vehicle.getType());
                statement.setInt(3, vehicle.getPerRent());
                statement.setString(4, vehicle.getVehicleId());
                statement.executeUpdate();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void work(Cars cars) {
        System.out.println("1. 轿车   2. 客车   3. 卡车");
        System.out.print("请选择你要修改的车的类型: ");
        int type = scanner.nextInt();
        ShowVehicle showVehicle = new ShowVehicle();
        showVehicle.show(cars.getList(type));
        System.out.print("请输入你要修改的车的车牌号: ");
        String vehicleId = scanner.next();
        for (int i = 0; i < cars.getList(type).size(); i++) {
            if (cars.getList(type).get(i).getVehicleId().equals(vehicleId)) {
                while (true) {
                    System.out.println("1.品牌 2.型号 3.日租金 0.退出");
                    System.out.print("请选择你要修该什么: ");
                    int choice = scanner.nextInt();
                    if (choice == 1) {
                        System.out.print("输入你所改的品牌: ");
                        String brand = scanner.next();
                        cars.getList(type).get(i).setBrand(brand);
                    } else if (choice == 2) {
                        System.out.print("输入你所改的型号: ");
                        String t = scanner.next();
                        cars.getList(type).get(i).setType(t);
                    } else if (choice == 3) {
                        System.out.print("请输入你所改的日租金: ");
                        int perRent = scanner.nextInt();
                        cars.getList(type).get(i).setPerRent(perRent);
                    } else {
                        System.out.println("修改完成!");
                        break;
                    }
                }
                Vehicle updatedVehicle = cars.getList(type).get(i);
                updateVehicleInDatabase(updatedVehicle); // 更新数据库中的车辆信息
            }
        }
    }
}
